package cn.itcast.wushangxiantu.Fragment.home;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.itcast.wushangxiantu.BaseAdapter.SenLinAdapter;
import cn.itcast.wushangxiantu.UserData.HuoDeNumber;
import cn.itcast.wushangxiantu.UserData.User;
import cn.itcast.wushangxiantu.UserData.UserSenLin;
import cn.itcast.wushangxiantu.UserData.UserValue;
import cn.itcast.wushangxiantu.Activity.Login;
import cn.itcast.wushangxiantu.MessageEvent;
import cn.itcast.wushangxiantu.OkhttpUtil;
import cn.itcast.wushangxiantu.R;
import cn.itcast.wushangxiantu.ToastUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

@SuppressLint("ValidFragment")
public class SenLin extends Fragment implements View.OnClickListener {
    private View view;
    private Context context;
    private TextView tvJinRu;
    private Spinner snDengJi;
    private Spinner snQuYu;
    private TextView tvBiaoTi;
    private TextView tvDiFang;
    private TextView tvWofang;
    private LinearLayout flSenLin;
    private ListView lvSenLinXinXi;
    private TextView tvGuaji;
    private RelativeLayout rl;
    private UserValue value;
    private int dengji = 1;
    private NeedStopThread thread;
    private UserSenLin senLin;
    private Button btnYueKa;
    private Button btnLiXian;

    private boolean Working = false;
    private static List<UserSenLin> lists;
    SenLinAdapter senLinAdapter;
    private ScrollView scrollView;
    private TextView tvHuoDe;

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_sen_lin, container, false);
        initView(view);
        return view;
    }

    public static List<UserSenLin> getLists() {
        return lists;
    }

    public static void setLists(List<UserSenLin> lists) {
        SenLin.lists = lists;
    }

    public SenLin(Context context) {
        this.context = context;
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    private void initView(View view) {
        tvJinRu = (TextView) view.findViewById(R.id.tvJinRu);
        snDengJi = (Spinner) view.findViewById(R.id.snDengJi);
        snQuYu = (Spinner) view.findViewById(R.id.snQuYu);
        tvBiaoTi = (TextView) view.findViewById(R.id.tvBiaoTi);
        tvDiFang = (TextView) view.findViewById(R.id.tvDiFang);
        tvWofang = (TextView) view.findViewById(R.id.tvWofang);
        flSenLin = (LinearLayout) view.findViewById(R.id.flSenLin);
        lvSenLinXinXi = (ListView) view.findViewById(R.id.lvSenLinXinXi);
        tvGuaji = (TextView) view.findViewById(R.id.tvGuaji);
        rl = (RelativeLayout) view.findViewById(R.id.rl);
        btnLiXian=(Button)view.findViewById(R.id.btnLiXian);
        btnLiXian.setOnClickListener(this);
        btnYueKa=(Button)view.findViewById(R.id.btnYueKa);
        btnYueKa.setOnClickListener(this);
        lists = new ArrayList<>();
        value = new UserValue(Login.getUser());
        int num = 1;
        tvDiFang.setText("敌方\n生命值：" + num * 80 + "\t\t\t防御值：" + (int) num * 12 + "\n" +
                "攻击力：" + num * 8 + "\t\t\t暴击率：" + (0) + "\n" +
                "恢复：" + num * 1 + "\t\t\t穿透：" + num * 1 + "\n" +
                "命中：" + 0 + "\t\t\t闪避：" + 0);
        tvWofang.setText("我方\n生命值：" + value.getSm() + "\t\t\t防御值：" + value.getFy() + "\n" +
                "攻击力：" + value.getGj() + "\t\t\t暴击率：" + value.getBj() + "\n" +
                "恢复：" + value.getHf() + "\t\t\t穿透：" + value.getCt() + "\n" +
                "命中：" + value.getMz() + "\t\t\t闪避：" + value.getSb());
        if (senLinAdapter == null) {
            senLinAdapter = new SenLinAdapter(context);
        }
        lvSenLinXinXi.setAdapter(senLinAdapter);

        tvJinRu.setOnClickListener(this);
        tvGuaji.setOnClickListener(this);
        scrollView = (ScrollView) view.findViewById(R.id.scrollView);
        SharedPreferences sp = Login.getSp();
        int item1 = sp.getInt("item1", 0);
        int item2 = sp.getInt("item2", 0);
        snQuYu.setSelection(item1);
        snDengJi.setSelection(item2);
        tvBiaoTi.setText(snDengJi.getSelectedItem().toString() + snQuYu.getSelectedItem().toString());
        num = snDengJi.getSelectedItemPosition() * 10;
        num += snQuYu.getSelectedItemPosition() * 2 + 1;
        ToastUtil.toast(context, "已进入" + num + "级" + tvBiaoTi.getText().toString());
        String content = "";
        dengji = num;
        if (num <= 11) {
            int gail = (int) (num * 0.3);
            content = "敌方\n生命值：" + num * 80 + "\t\t\t防御值：" + (int) num * 2 + "\n" +
                    "攻击力：" + num * 8 + "\t\t\t暴击率：" + (gail) + "\n" +
                    "恢复：" + num * 1 + "\t\t\t穿透：" + num * 1 + "\n" +
                    "命中：" + gail + "\t\t\t闪避：" + gail;
        } else if (num <= 21) {
            int gail = (int) (num * 0.3);
            content = "敌方\n生命值：" + num * 109 + "\t\t\t防御值：" + (int) num * 6 + "\n" +
                    "攻击力：" + num * 12 + "\t\t\t暴击率：" + (gail) + "\n" +
                    "恢复：" + num * 3 + "\t\t\t穿透：" + num * 3 + "\n" +
                    "命中：" + gail + "\t\t\t闪避：" + gail;
        } else if (num <= 31) {
            int gail = (int) (num * 0.3);
            content = "敌方\n生命值：" + num * 150 + "\t\t\t防御值：" + (int) num * 15 + "\n" +
                    "攻击力：" + num * 30 + "\t\t\t暴击率：" + (gail) + "\n" +
                    "恢复：" + num * 7 + "\t\t\t穿透：" + num * 7 + "\n" +
                    "命中：" + gail + "\t\t\t闪避：" + gail;
        } else if (num <= 41) {
            int gail = (int) (num * 0.3);
            content = "敌方\n生命值：" + num * 165 + "\t\t\t防御值：" + (int) num * 18 + "\n" +
                    "攻击力：" + num * 37 + "\t\t\t暴击率：" + (gail) + "\n" +
                    "恢复：" + num * 8 + "\t\t\t穿透：" + num * 8 + "\n" +
                    "命中：" + gail + "\t\t\t闪避：" + gail;
        } else if (num <= 51) {
            int gail = (int) (num * 0.3);
            content = "敌方\n生命值：" + num * 175 + "\t\t\t防御值：" + (int) num * 20 + "\n" +
                    "攻击力：" + num * 40 + "\t\t\t暴击率：" + (gail) + "\n" +
                    "恢复：" + num * 10 + "\t\t\t穿透：" + num * 10 + "\n" +
                    "命中：" + gail + "\t\t\t闪避：" + gail;
        } else if (num <= 61) {
            int gail = (int) (num * 0.4);
            content = "敌方\n生命值：" + num * 180 + "\t\t\t防御值：" + (int) num * 22 + "\n" +
                    "攻击力：" + num * 44 + "\t\t\t暴击率：" + (gail) + "\n" +
                    "恢复：" + num * 11 + "\t\t\t穿透：" + num * 11 + "\n" +
                    "命中：" + gail + "\t\t\t闪避：" + gail;
        } else if (num <= 81) {
            int gail = (int) (num * 0.4);
            content = "敌方\n生命值：" + num * 200 + "\t\t\t防御值：" + (int) num * 30 + "\n" +
                    "攻击力：" + num * 60 + "\t\t\t暴击率：" + (gail) + "\n" +
                    "恢复：" + num * 15 + "\t\t\t穿透：" + num * 15 + "\n" +
                    "命中：" + gail + "\t\t\t闪避：" + gail;
        } else {
            int gail = (int) (num * 0.5);
            content = "敌方\n生命值：" + num * 210 + "\t\t\t防御值：" + num * 32 + "\n" +
                    "攻击力：" + num * 65 + "\t\t\t暴击率：" + gail + "\n" +
                    "恢复：" + num * 16 + "\t\t\t穿透：" + num * 16 + "\n" +
                    "命中：" + gail + "\t\t\t闪避：" + gail;
        }
        tvDiFang.setText(content);
        tvHuoDe = (TextView) view.findViewById(R.id.tvHuoDe);
        tvHuoDe.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvJinRu:
                if (tvGuaji.getText().toString().trim().equals("取消挂机")) {
                    ToastUtil.toast(context, "请先取消挂机");
                    return;
                }
                tvBiaoTi.setText(snDengJi.getSelectedItem().toString() + snQuYu.getSelectedItem().toString());
                int num = snDengJi.getSelectedItemPosition() * 10;
                num += snQuYu.getSelectedItemPosition() * 2 + 1;
                ToastUtil.toast(context, "已进入" + num + "级" + tvBiaoTi.getText().toString());
                String content = "";
                dengji = num;
                if (num <= 11) {
                    int gail = (int) (num * 0.3);
                    content = "敌方\n生命值：" + num * 80 + "\t\t\t防御值：" + (int) num * 2 + "\n" +
                            "攻击力：" + num * 8 + "\t\t\t暴击率：" + (gail) + "\n" +
                            "恢复：" + num * 1 + "\t\t\t穿透：" + num * 1 + "\n" +
                            "命中：" + gail + "\t\t\t闪避：" + gail;
                } else if (num <= 21) {
                    int gail = (int) (num * 0.3);
                    content = "敌方\n生命值：" + num * 109 + "\t\t\t防御值：" + (int) num * 6 + "\n" +
                            "攻击力：" + num * 12 + "\t\t\t暴击率：" + (gail) + "\n" +
                            "恢复：" + num * 3 + "\t\t\t穿透：" + num * 3 + "\n" +
                            "命中：" + gail + "\t\t\t闪避：" + gail;
                } else if (num <= 31) {
                    int gail = (int) (num * 0.3);
                    content = "敌方\n生命值：" + num * 150 + "\t\t\t防御值：" + (int) num * 15 + "\n" +
                            "攻击力：" + num * 30 + "\t\t\t暴击率：" + (gail) + "\n" +
                            "恢复：" + num * 7 + "\t\t\t穿透：" + num * 7 + "\n" +
                            "命中：" + gail + "\t\t\t闪避：" + gail;
                } else if (num <= 41) {
                    int gail = (int) (num * 0.3);
                    content = "敌方\n生命值：" + num * 165 + "\t\t\t防御值：" + (int) num * 18 + "\n" +
                            "攻击力：" + num * 37 + "\t\t\t暴击率：" + (gail) + "\n" +
                            "恢复：" + num * 8 + "\t\t\t穿透：" + num * 8 + "\n" +
                            "命中：" + gail + "\t\t\t闪避：" + gail;
                } else if (num <= 51) {
                    int gail = (int) (num * 0.3);
                    content = "敌方\n生命值：" + num * 175 + "\t\t\t防御值：" + (int) num * 20 + "\n" +
                            "攻击力：" + num * 40 + "\t\t\t暴击率：" + (gail) + "\n" +
                            "恢复：" + num * 10 + "\t\t\t穿透：" + num * 10 + "\n" +
                            "命中：" + gail + "\t\t\t闪避：" + gail;
                } else if (num <= 61) {
                    int gail = (int) (num * 0.4);
                    content = "敌方\n生命值：" + num * 180 + "\t\t\t防御值：" + (int) num * 22 + "\n" +
                            "攻击力：" + num * 44 + "\t\t\t暴击率：" + (gail) + "\n" +
                            "恢复：" + num * 11 + "\t\t\t穿透：" + num * 11 + "\n" +
                            "命中：" + gail + "\t\t\t闪避：" + gail;
                } else if (num <= 81) {
                    int gail = (int) (num * 0.4);
                    content = "敌方\n生命值：" + num * 200 + "\t\t\t防御值：" + (int) num * 30 + "\n" +
                            "攻击力：" + num * 60 + "\t\t\t暴击率：" + (gail) + "\n" +
                            "恢复：" + num * 15 + "\t\t\t穿透：" + num * 15 + "\n" +
                            "命中：" + gail + "\t\t\t闪避：" + gail;
                } else {
                    int gail = (int) (num * 0.5);
                    content = "敌方\n生命值：" + num * 210 + "\t\t\t防御值：" + num * 32 + "\n" +
                            "攻击力：" + num * 65 + "\t\t\t暴击率：" + gail + "\n" +
                            "恢复：" + num * 16 + "\t\t\t穿透：" + num * 16 + "\n" +
                            "命中：" + gail + "\t\t\t闪避：" + gail;
                }
                SharedPreferences.Editor editor = Login.getSp().edit();
                editor.putInt("item1", snQuYu.getSelectedItemPosition());
                editor.putInt("item2", snDengJi.getSelectedItemPosition());
                editor.commit();
                tvDiFang.setText(content);
                break;
            case R.id.tvGuaji:
                if (!Working) {
                    if (Login.getUser().getDj() >= 20) {
                        ToastUtil.toastLong(context, "正在" + tvBiaoTi.getText() + "挂机中，别忘了现在两边都可以挂机哦");
                    } else {
                        ToastUtil.toastLong(context, "正在" + tvBiaoTi.getText() + "挂机中【二十级可开启两边同时挂机】");
                    }
                    try {
                        tvGuaji.setText("取消挂机");
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Working = true;
                    if (thread == null) {
                        thread = new NeedStopThread();
                        thread.start();
                    }
                    if (!thread.isAlive()) {
                        thread = null;
                        thread = new NeedStopThread();
                        thread.start();
                    }
                } else {
                    Working = false;
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    tvGuaji.setText("开始挂机");
                    //停止动画

                }
                break;
            case R.id.tvHuoDe:
                List<HuoDeNumber>list=new ArrayList<>();
                list.add(new HuoDeNumber("魔核",0));
                list.add(new HuoDeNumber("石魂",0));
                list.add(new HuoDeNumber("修为",0));
                for (int i = 0; i < lists.size(); i++) {
                    if (lists.get(i).getStw().equals("OK")){
                        list.get(2).setNumber(list.get(2).getNumber()+lists.get(i).getJy2());
                        for (int j = 0; j < list.size(); j++) {
                            if (lists.get(i).getWp().equals(list.get(j).getName())){
                                list.get(j).setNumber(list.get(j).getNumber()+1);
                                break;
                            }else if (j==list.size()-1){
                                list.add(new HuoDeNumber(lists.get(i).getWp(),1));
                                break;
                            }
                        }
                        if (lists.get(i).getShihun()==1) {
                            list.get(1).setNumber(list.get(1).getNumber() + 1);
                        }
                    }
                }
                String xinxi="";
                for (int i = 0; i < list.size(); i++) {
                    xinxi+=list.get(i).getName()+"*"+list.get(i).getNumber()+"\n";
                }
                GeneralDialog("掉落详情",xinxi);
                break;
            case R.id.btnYueKa:
                getYueKa();
                break;
            case R.id.btnLiXian:
                setLiXian();
                break;
        }
    }
    public void GeneralDialog(String head, String content) {
        /**
         * 普通对话框
         * 1标题
         * 2内容
         */
        AlertDialog dialog;
        AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .setTitle(head)

                .setMessage(content)
                .setNeutralButton("清空", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        lists.clear();
                        senLinAdapter.notifyDataSetChanged();
                    }
                })
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                });
        dialog = builder.create();
        dialog.show();
    }
    public void GeneralDialogYueKa(String head, String content) {
        /**
         * 普通对话框
         * 1标题
         * 2内容
         */
        AlertDialog dialog;
        AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .setTitle(head)

                .setMessage(content)
                .setNeutralButton("续费", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        setYueKa();
                    }
                })
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                });
        dialog = builder.create();
        dialog.show();
    }
    public void getSenLinGuaji(int dengji) {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "userName=" + Login.getUser().getUsernumber() + "&need=guaji" + "&dengji=" + dengji, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                try {
                    Log.v("nongtianganhuo1", e.getMessage());
                }catch (Exception e1){

                }
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String src = response.body().string();
                Log.v("nongtianganhuo2", src);
                UserSenLin user = null;
                try {
                    user = new Gson().fromJson(src, UserSenLin.class);
                } catch (Exception e) {

                }
                Message message = new Message();
                message.obj = user;
                message.what = 1;
                handler.sendMessage(message);
            }
        });
    }
    public void setYueKa() {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "userName=" + Login.getUser().getUsernumber() + "&need=setYueKa" +"&passWord="+Login.getUser().getPassword(), new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                try {
                    Log.v("setYueKa", e.getMessage());
                }catch (Exception e1){

                }
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String src = response.body().string();
                Log.v("setYueKa", src);
                User user = null;
                try {
                    user = new Gson().fromJson(src, User.class);
                } catch (Exception e) {

                }
                Message message = new Message();
                message.obj = user;
                message.what = 2;
                handler.sendMessage(message);
            }
        });
    }
    public void getYueKa() {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "userNumber=" + Login.getUser().getUsernumber() + "&need=getyueka" , new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                try {
                    Log.v("getYueKa", e.getMessage());
                }catch (Exception e1){

                }
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String src = response.body().string();
                Log.v("getYueKa", src);
                User user = null;
                try {
                    user = new Gson().fromJson(src, User.class);
                } catch (Exception e) {

                }
                Message message = new Message();
                message.obj = user;
                message.what = 3;
                handler.sendMessage(message);
            }
        });
    }
    public void setLiXian() {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "userNumber=" + Login.getUser().getUsernumber() + "&need=setlixian2" + "&id=" + dengji, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                try {
                    Log.v("lixian1", e.getMessage());
                }catch (Exception e1){

                }
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String src = response.body().string();
                Log.v("lixian2", src);
                User user = null;
                try {
                    user = new Gson().fromJson(src, User.class);
                } catch (Exception e) {

                }
                Message message = new Message();
                message.obj = user;
                message.what = 2;
                handler.sendMessage(message);
            }
        });
    }
    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message message) {
            switch (message.what){
                case 1:
                    senLin = (UserSenLin) message.obj;
                    if (senLin != null) {
                        String jieguo = senLin.getStw().trim();
                        if (jieguo.contains("NO") || jieguo.contains("OK")) {
                            if (jieguo.equals("OK")) {
                                Login.getUser().setDj(senLin.getDj());
                                Login.getUser().setJy(senLin.getJy1());
                                EventBus.getDefault().post(new MessageEvent("SenLin"));
                                value = new UserValue(Login.getUser());
                                tvWofang.setText("我方\n生命值：" + value.getSm() + "\t\t\t防御值：" + value.getFy() + "\n" +
                                        "攻击力：" + value.getGj() + "\t\t\t暴击率：" + value.getBj() + "\n" +
                                        "恢复：" + value.getHf() + "\t\t\t穿透：" + value.getCt() + "\n" +
                                        "命中：" + value.getMz() + "\t\t\t闪避：" + value.getSb());
                            }
                            if (senLin.getShihun() == 1) {
                                MessageEvent messageEvent = new MessageEvent("xinxi");
                                messageEvent.setContent("恭喜玩家" + Login.getUser().getName() + "在魔界历练获得石魂一枚");
                                EventBus.getDefault().post(messageEvent);
                            }
                            lists.add(senLin);
                            if (tvGuaji.getText().toString().equals("取消挂机")) {
                                senLinAdapter.notifyDataSetChanged();
                            }
                        } else if (!(jieguo.contains("NO"))) {
                            ToastUtil.toast(context, senLin.getStw());
//                    //停止线程
//                    Working = false;
//                    try {
//                        Thread.sleep(1000);
//                        if (thread != null) {
//                            thread = null;
//                            iv1.clearAnimation();
//                            iv2.clearAnimation();
//                        }
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                    tvGuaji.setText("开始挂机");
//                    //停止动画
                        }
                    } else {
                        ToastUtil.toast(context, "服务器坏掉了");
                    }
                    break;
                case 2:
                    User user= (User) message.obj;
                    if (null!=user){
                        ToastUtil.toast(context,user.getStw());
                    }else {
                        ToastUtil.toast(context);
                    }
                    break;
                case 3:
                    user= (User) message.obj;
                    if (null!=user){
                        GeneralDialogYueKa("离线修为详情【续时30天所需30技能残页】",user.getStw());
                    }else {
                        ToastUtil.toast(context);
                    }
                    break;
            }
            return false;
        }
    });

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (thread != null) {
            thread.interrupt();
            Working = false;
            thread = null;
        }
    }

    class NeedStopThread extends Thread {
        @Override
        public void run() {
            while (Working) {
                try {
                    sleep(5000);
                    if (Working) {
                        getSenLinGuaji(dengji);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }

}